<template>
    <div class="content">
        <div class="top">
            <div class="wrap">
                <span> 您的建议是?</span>
                <span> 我们期待为您带来最好的服务</span>
            </div>
        </div>

        <div class="middle">
            <div class="body">
                <div class="select-func">
                    <span>请选择您要建议的功能</span>
                </div>
                <div class="specific-func">
                    <div class="func-components">
                        <div :class="{ active: selectedFunction === 'delivery' }" @click="selectFunction('delivery')">
                            <i class="iconfont">&#xe608;</i>
                            <span>收派服务</span>
                        </div>
                        <div :class="{ active: selectedFunction === 'packaging' }" @click="selectFunction('packaging')">
                            <i class="iconfont">&#xe633;</i>
                            <span>包装物料</span>
                        </div>
                        <div :class="{ active: selectedFunction === 'pricing' }" @click="selectFunction('pricing')">
                            <i class="iconfont">&#xe932;</i>
                            <span>价格发票</span>
                        </div>
                        <div :class="{ active: selectedFunction === 'additional' }"
                            @click="selectFunction('additional')">
                            <i class="iconfont">&#xe66f;</i>
                            <span>附加服务</span>
                        </div>
                        <div :class="{ active: selectedFunction === 'other' }" @click="selectFunction('other')">
                            <i class="iconfont">&#xe6fe;</i>
                            <span>其他</span>
                        </div>
                    </div>
                </div>
                <div class="feedback">
                    <el-input v-model="Feedback" style="width: 100%" :rows="4" type="textarea"
                        placeholder="欢迎您反馈对飞鸟官网的使用建议，帮助我们做的更好(必填)" />
                </div>
                <div class="img-wrap">
                    <div class="snipaste-tip">
                        <span>附加截图<text>（选填）</text></span>

                    </div>
                    <div class="paste">
                        <el-upload class="avatar-uploader" action="#" :auto-upload="true" :show-file-list="false"
                            :http-request="customUpload">
                            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </div>
                </div>
                <div class="more-info">
                    <div class="name">
                        <el-input v-model="userName" style="width: 30%" placeholder="姓名 (选填)" />
                    </div>
                    <div class="contact-way">
                        <el-input v-model="userContact" style="width: 30%" placeholder="联系方式 (选填)" />
                    </div>
                </div>

            </div>
        </div>

        <div class="bottom">
            <div class="text">
                <span>建议反馈可能无法及时回复您，如果您有紧急问题，请咨询<a href="">在线客服</a></span>

            </div>
            <div class="btn">
                <el-button class="my-button" type="default" @click="submitFeedback">提交</el-button>
            </div>

        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import type { UploadProps } from 'element-plus'

const imageUrl = ref<string>('')
let Feedback = ref<string>('')
const selectedFunction = ref<string>('')
const uploadedFileName = ref<string>('') // 存储上传后的文件名，用于可能的删除操作
const isUploading = ref<boolean>(false)
const userName = ref<string>('') // 添加姓名字段
const userContact = ref<string>('') // 添加联系方式字段

// 七牛云配置
const qiniuConfig = reactive({
  uploadDomain: 'https://up-z2.qiniup.com', // 七牛云上传域名
  accessDomain: 'https://cityexpress.yellowswimming.cn/', // 七牛云访问域名，需要替换为你的实际域名
  token: ''
})

const selectFunction = (functionName: string) => {
    selectedFunction.value = functionName
    console.log('Selected function:', selectedFunction.value)
}

// 获取七牛云上传凭证
const getQiniuToken = async () => {
  try {
    const response = await axios.get('http://localhost:8180/getUploadToken')
    if (response.data) {
      qiniuConfig.token = response.data
      return true
    }
    return false
  } catch (error) {
    console.error('获取上传凭证失败:', error)
    ElMessage.error('获取上传凭证失败，请重试')
    return false
  }
}

// 生成带时间戳的文件名
const generateFileName = (originalName: string) => {
  const timestamp = new Date().getTime()
  const ext = originalName.substring(originalName.lastIndexOf('.'))
  return `feedbackImg/feedback_${timestamp}${ext}`
}

// 上传文件到七牛云
const uploadToQiniu = async (file: File) => {
  // 获取上传凭证
  const tokenOk = await getQiniuToken()
  if (!tokenOk) return null

  // 生成文件名
  const fileName = generateFileName(file.name)
  uploadedFileName.value = fileName

  // 创建FormData
  const formData = new FormData()
  formData.append('token', qiniuConfig.token)
  formData.append('key', fileName)
  formData.append('file', file)

  try {
    isUploading.value = true
    const response = await axios.post(qiniuConfig.uploadDomain, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data && response.data.key) {
      // 上传成功，返回文件访问URL
      const fileUrl = qiniuConfig.accessDomain + response.data.key
      return fileUrl
    } else {
      ElMessage.error('文件上传失败')
      return null
    }
  } catch (error) {
    console.error('上传到七牛云失败:', error)
    ElMessage.error('文件上传失败，请重试')
    return null
  } finally {
    isUploading.value = false
  }
}

// 处理文件上传
const customUpload = (options: any) => {
  const file = options.file
  handleFileUpload(file)
  return false // 阻止el-upload默认上传行为
}

// 处理文件上传
const handleFileUpload = async (file: File) => {
  if (!beforeAvatarUpload(file as any)) return

  const fileUrl = await uploadToQiniu(file)
  if (fileUrl) {
    imageUrl.value = fileUrl
    ElMessage.success('图片上传成功')
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    // 检查文件类型，允许更多图片格式
    const isImage = /\.(jpeg|jpg|png|gif|bmp|webp)$/i.test(rawFile.name)
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    
    // 限制文件大小为5MB
    const isLt5M = rawFile.size / 1024 / 1024 < 5
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB!')
        return false
    }
    return true
}

// 删除已上传的文件
const deleteUploadedFile = async () => {
  if (!uploadedFileName.value) return
  console.log(uploadedFileName.value)

  try {
    // 调用后端删除文件的接口
    await axios.delete('http://localhost:8180/deleteQiniuFile', {
        params: {
        key: uploadedFileName.value
      }
    })
    console.log('文件已删除:', uploadedFileName.value)
  } catch (error) {
    console.error('删除文件失败:', error)
  }
}

// 提交表单时的处理函数
const submitFeedback = async () => {
    if (!selectedFunction.value) {
        ElMessage.warning('请选择您要建议的功能')
        return
    }
    
    if (!Feedback.value.trim()) {
        ElMessage.warning('请填写您的反馈内容')
        return
    }
    
    try {
        // 构建要提交的数据
        const feedbackData = {
            category: selectedFunction.value,
            content: Feedback.value,
            name: userName.value || '匿名用户', // 使用用户输入的姓名，如果没有则默认为匿名用户
            imageUrl: imageUrl.value || '',
            contact: userContact.value || '未提供联系方式', // 使用用户输入的联系方式，如果没有则默认为未提供

        }
        
        // 发送到后端API
        const response = await axios.post('http://localhost:8088/feedback/submit', feedbackData)
        
        if (response.data && response.data.status === 300) {
            ElMessage.success('感谢您的反馈！')
            // 重置表单
            selectedFunction.value = ''
            Feedback.value = ''
            imageUrl.value = ''
            uploadedFileName.value = ''
            userName.value = ''
            userContact.value = ''
        } else {
            ElMessage.error('提交失败，请重试')
            // 如果提交失败，可以考虑删除已上传的文件
            if (uploadedFileName.value) {
                await deleteUploadedFile()
            }
        }
    } catch (error) {
        console.error('Submit error:', error)
        ElMessage.error('网络错误，请稍后重试')
        // 如果提交失败，可以考虑删除已上传的文件
        if (uploadedFileName.value) {
            await deleteUploadedFile()
        }
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    margin-top: 1em;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped lang="less">
/* 在线链接服务仅供平台体验和调试使用，平台不承诺服务的稳定性，企业客户需下载字体包自行发布使用并做好备份。 */
@font-face {
    font-family: 'iconfont';
    /* Project id 4410292 */
    src: url('//at.alicdn.com/t/c/font_4410292_05vfocbydu39.woff2?t=1712827716036') format('woff2'),
        url('//at.alicdn.com/t/c/font_4410292_05vfocbydu39.woff?t=1712827716036') format('woff'),
        url('//at.alicdn.com/t/c/font_4410292_05vfocbydu39.ttf?t=1712827716036') format('truetype');
}
.avatar-uploader .avatar {

//   width: 178px;
  height: 178px;
  display: block;
}
.iconfont {
    font-family: "iconfont" !important;
    font-size: 16px;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;
}

.content {
    background-color: white;
    position: absolute;
    width: 150vh;
    height: 82vh;
    margin: 10px 0 0 0;
    right: 4px;
    display: flex;
    flex-direction: column;

    .top {
        flex: 1;

        .wrap {
            display: flex;
            flex-direction: column;
            padding: 1vh 0 0.5vh 1.5vw;

            span:nth-child(1) {
                font-weight: 500;
                font-size: 1.1rem;
                margin-bottom: 5px;
            }

            span:nth-child(2) {
                font-size: 0.7rem;
                color: grey;
            }
        }
    }

    .middle {
        flex: 8;

        display: flex;
        justify-content: center;
        align-items: center;

        .body {
            width: 96%;
            height: 96%;
            // background-color: rgb(235, 234, 232);
            border-radius: 10px 10px 10px;
            display: flex;
            flex-direction: column;

            .select-func {
                flex: 1;

                span {
                    font-size: 0.8rem;

                }
            }

            .specific-func {
                flex: 1.5;
                margin-top: 10px;
                display: flex;
                align-items: center;
                justify-content: flex-start;

                .func-components {
                    width: 50%;
                    height: 100%;

                    display: flex;
                    justify-content: space-around;
                    align-items: center;

                    div {
                        flex: 1;
                        height: 100%;
                        background-color: #f4f5f7;
                        margin-right: 2px;
                        cursor: pointer; 
                        transition: all 0.3s ease; 

                        span {
                            font-size: 0.7rem;
                            margin-left: 2px;
                        }

                        display: flex;
                        justify-content: center;
                        align-items: center;
                        &.active {
                            background-color: #3491c7;
                            color: white;
                        }
                    }
                }
            }

            .feedback {
                flex: 4;
                // background-color:brown;
                margin-top: 10px;
                display: flex;
                justify-content: center;
                align-items: center;

                :deep(.el-textarea__inner) {
                    font-size: 0.8rem;
                }
            }

            .img-wrap {
                flex: 5;
                // background-color: grey;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                .snipaste-tip {
                    flex: 1;
                    width: 100%;

                    margin-top: 10px;

                    span {
                        font-size: 0.8rem;

                        text {
                            color: grey;
                            margin-left: 5px;
                        }
                    }
                }

                .paste {
                    width: 100%;
                    flex: 3;
                    // .avatar-uploader {
                    //     width: 120px !important;
                    //     height: 120px !important;
                    //     background-color: #f7f8fa;
                    //     display: flex;
                    //     justify-content: center;
                    //     align-items: center;
                    // }

                    // .avatar-uploader .el-upload:hover {
                    //     border-color: var(--el-color-primary);
                    // }

                    // .el-icon.avatar-uploader-icon {
                    //     font-size: 28px;
                    //     color: #909399;
                    //     width: 100%;
                    //     height: 100%;
                    //     display: flex;
                    //     justify-content: center;
                    //     align-items: center;
                    // }

                    // .avatar {
                    //     width: 178px;
                    //     height: 178px;
                    //     display: block;
                    // }
                }
            }

            .more-info {
                flex: 3;
                display: flex;
                flex-direction: column;
                justify-content: center;

                .name {
                    margin-bottom: 5px;

                    :deep(.el-input__wrapper) {
                        background-color: #f7f8fa !important;
                        border: red !important;
                    }

                    :deep(.el-input__inner) {
                        font-size: 0.7rem;
                        border: 0 !important;
                    }
                }

                .contact-way {
                    :deep(.el-input__wrapper) {
                        background-color: #f7f8fa !important;
                    }

                    :deep(.el-input__inner) {
                        font-size: 0.7rem;
                    }
                }
            }
        }
    }

    .bottom {
        flex: 2;
        display: flex;
        flex-direction: column;

        .text {

            flex: 1;
            display: flex;
            align-items: center;

            span {
                color: grey;
                font-size: 0.8rem;
                margin-left: 10px;
            }
        }

        .btn {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;

            .my-button {
                width: 20%;
                background-color: #ff4d4d;
                color: white;
            }

        }
    }
}
</style>
